package com.zhengtoudai.ui.fragment;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.squareup.otto.Bus;
import com.zhengtoudai.R;
import com.zhengtoudai.base.App;
import com.zhengtoudai.base.BaseActivity;
import com.zhengtoudai.http.HttpUtil;
import com.zhengtoudai.injector.component.DaggerActivityComponent;
import com.zhengtoudai.injector.module.ActivityModule;
import com.zhengtoudai.otto.RequestTransferEvent;
import com.zhengtoudai.ui.bean.RedeemTransfer;
import com.zhengtoudai.ui.bean.Result;
import com.zhengtoudai.ui.presenter.RequestTransferPresenterImpl;
import com.zhengtoudai.ui.presenter.TransferDialogPresenterImpl;
import com.zhengtoudai.ui.view.CommonView;
import com.zhengtoudai.ui.view.TransferDialogView;
import com.zhengtoudai.util.AbToastUtil;
import com.zhengtoudai.util.CashierInputFilter;
import com.zhengtoudai.util.Tool;

import java.util.Calendar;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/8/30 0030.
 */

public class TransferDialogFragment extends DialogFragment implements TransferDialogView,CommonView{

    @Bind(R.id.edt_transfer_money)
    EditText mEdtTransferMoney;
    @Bind(R.id.tv_transfer_money)
    TextView mTvTransferMoney;
    @Bind(R.id.tv_end_time)
    TextView mTvEndTime;
    @Bind(R.id.tv_handling_charge)
    TextView mTvHandlingCharge;
    private String etenderId;

    @Inject
    TransferDialogPresenterImpl mInfoPresenter;

    @Inject
    RequestTransferPresenterImpl mRequestPresenter;

    @Inject
    Bus mBus;

     private BaseActivity mActivity;

    private DatePickerDialog endDateDialog;

    private RedeemTransfer mTransfer;

    private String endDate;
    public static TransferDialogFragment getInstance(String etenderId) {
        TransferDialogFragment fragment = new TransferDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("etenderId", etenderId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity= (BaseActivity) getActivity();
        setCancelable(false);

        etenderId = getArguments().getString("etenderId");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_delegatio_nominis, null);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
        mBus.unregister(this);
    }

    private void init(){
        DaggerActivityComponent.builder()
                .appComponent(App.mApp.getAppComponent())
                .activityModule(new ActivityModule(getActivity()))
                .build()
                .inject(this);
        mBus.register(this);
        mInfoPresenter.attachView(this);
        mRequestPresenter.attachView(this);
        mInfoPresenter.redeemTransfer(etenderId);

        mEdtTransferMoney.setFilters(new InputFilter[]{new CashierInputFilter()});
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
                    getDialog().cancel();
                    return true;
                }
                return false;
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mInfoPresenter.detachView();
        mRequestPresenter.detachView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_end_time,R.id.btn_cancel, R.id.btn_affirm})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            case R.id.tv_end_time:
                if (endDateDialog == null) {
                    int year, month, day;
                    if (TextUtils.isEmpty(endDate)) {
                        Calendar calendar = Calendar.getInstance();
                        year = calendar.get(Calendar.YEAR);
                        month = calendar.get(Calendar.MONTH);
                        day = calendar.get(Calendar.DAY_OF_MONTH);

                    } else {
                        String[] starts = endDate.split("-");
                        year = Integer.parseInt(starts[0]);
                        month = Integer.parseInt(starts[1]);
                        day = Integer.parseInt(starts[2]);
                    }
                    endDateDialog = new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            if (monthOfYear<11){
                                monthOfYear++;
                            }else{
                                year++;
                                monthOfYear=1;
                            }
                            endDate = year + "-" + monthOfYear + "-" + dayOfMonth;
                            mTvEndTime.setText(endDate);
                        }
                    }, year, month, day);

                }
                endDateDialog.show();
                break;
            case R.id.btn_cancel:
                getDialog().cancel();
                break;
            case R.id.btn_affirm:
                if (mTransfer==null){
                    mInfoPresenter.redeemTransfer(etenderId);
                    AbToastUtil.showToast(mActivity,"正在获取转让信息...");
                    return;
                }
                String money=mEdtTransferMoney.getText().toString();
                if (TextUtils.isEmpty(money)||Double.parseDouble(money)==0){
                    AbToastUtil.showToast(mActivity,"请输入转让金额");
                }else if (Double.parseDouble(money)>Double.parseDouble(mTransfer.getResult().getMaxTransferMoney())){
                    AbToastUtil.showToast(mActivity,"请转让金额不得大于最大转让金额");
                }else if (endDate==null){
                    AbToastUtil.showToast(mActivity,"请输入选择结束时间");
                }else {
                    mRequestPresenter.requestTransfer(money,etenderId,endDate);
                }

                break;
        }
    }

    @Override
    public void onResult(RedeemTransfer transfer) {
        if (transfer.getCode().equals("200")){
            mTransfer=transfer;
            mEdtTransferMoney.setText(transfer.getResult().getTransferMoney()+"");
            mEdtTransferMoney.setSelection(mEdtTransferMoney.getText().length());
            mTvTransferMoney.setText(transfer.getResult().getMaxTransferMoney()+"元");
            mTvHandlingCharge.setText(transfer.getResult().getTransferFee()+"元");

        }else{
            AbToastUtil.showToast(getContext(),transfer.getMessage());
        }
        //mEdtTransferMoney.setText(tr);
    }

    @Override
    public void showDialog() {
        mActivity.showProgressDialog("正在转让中...");
    }

    @Override
    public void onResult(Result result) {
        if (result.getCode()==200){
            mBus.post(new RequestTransferEvent());
            getDialog().cancel();
        }
        AbToastUtil.showToast(mActivity,result.getMessage());
    }

    @Override
    public void onFailure(Throwable e) {
        HttpUtil.disposeOnFailure(getContext(),e);
    }

    @Override
    public void dismissDialog() {
        mActivity.dismissProgressDialog();
    }
}
